package com.hcb.tonguetiphealth.view;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.hcb.tonguetiphealth.global.Global;
import com.hcb.tonguetiphealth.manager.JSONManager;
import com.hcb.tonguetiphealth.model.User;
import com.hcb.tonguetiphealth.service.TongueTipHealthService;
import com.hcb.tonguetiphealth.service.TongueTipHealthServiceLiuYan;
import com.hcb.tonguetiphealth.util.HttpUtils;
import com.hcb.tonguetiphealth.util.MessageWhat;
import com.hcb.tonguetiphealth.util.StringUtils;
import com.hcb.tonguetiphealth.widget.homepage.HomepageChatWidget2;

public class ChatActivity extends AbstractActivity {
	private static final String TAG = "ChatActivity";
	private static final String url_acceptChat = Global.URL + Global.servlet_acceptChat;
	private static final String url_refuseChat = Global.URL + Global.servlet_refuseChat;
	private HomepageChatWidget2 homepageChatWidget2;
	private User user;
	private Handler chatHandler;
	
	private String fileName = "";
	private LinearLayout parent;
	private LayoutInflater inflater;
	
	private String response; 
	
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      chatHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch(msg.what) {
			case MessageWhat.CHAT_NOTIFICATION:
				user = (User)msg.obj;
				getIntent().putExtra("from", "TongueTipHealthService");
				getIntent().putExtra("user", user);
				break;
			case MessageWhat.CHAT_NOTIFICATION_LIUYAN:
				response = (String)msg.obj;
				System.out.println("activity response:"+response);
				getIntent().putExtra("from", "TongueTipHealthServiceLiuYan");
				getIntent().putExtra("response", response);
				break;
			}
		}
      };
      TongueTipHealthService.setChatHandler(chatHandler);
      TongueTipHealthServiceLiuYan.setChatHandler(chatHandler);
      
      inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);  
      /*parent = Global.parentLinearLayout;
      if(parent != null) {
    	  parent.removeAllViews();
      }*/
      if(Global.parentLinearLayout != null) {
    	  Global.parentLinearLayout.removeAllViews();
      }
      Global.parentLinearLayout = parent = (LinearLayout) inflater.inflate(R.layout.chat_parent, null);

      if(Global.homepageChatWidget2 == null) {
		  Global.homepageChatWidget2 = new HomepageChatWidget2(this);
	  }
	 
      //homepageChatWidget2.setProcessing(true);
      setContentView(parent);
      if(Global.chatActivity[0] != null) {
    	  Global.chatActivity[0].finish();
    	  Global.chatActivity[1] = this;
		  Global.chatActivity[0] = null;
      } else {
    	  Global.chatActivity[0] = this;
    	  if(Global.chatActivity[1] != null) {
    		  Global.chatActivity[1].finish();
    		  Global.chatActivity[1] = null;
    	  }
    	   
      }
      parent.addView(Global.homepageChatWidget2);
      
      String from = getIntent().getStringExtra("from");
	    if(from != null && from.equals("user")) {
			getIntent().putExtra("from", "");
	    	user = (User)getIntent().getSerializableExtra("user");
	    	Global.homepageChatWidget2.initCurrentUser(user);
	    }
  }
  
  private void acceptOrRefuseChatDialog() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("聊天请求");
		//builder.setIcon(R.drawable.what);
		builder.setMessage(user.getRealName() + "向你发起聊天");
		builder.setCancelable(false);
		builder.setPositiveButton("拒绝", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				homepageChatWidget2.setCurrentUser(null);
				acceptOrRefuseChat(2);
			}
		});
		builder.setNegativeButton("同意", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int id) {
				acceptOrRefuseChat(1);
			}
		});
		builder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				System.out.println("OnCancelListener -----------------------------");
			    acceptOrRefuseChat(2);
				TongueTipHealthService.setProcessing(true);
			}
		});
		builder.show();
		
	}

  private void acceptOrRefuseChat(final int flag) {
		new Thread() {
			public void run() {
				String response = null;
				String url = flag==1? url_acceptChat : url_refuseChat;
				try {
					List <NameValuePair> params = new ArrayList <NameValuePair>();
					params.add(new BasicNameValuePair("chatId", user.getChatId()));
					params.add(new BasicNameValuePair("userName", Global.user==null? "":Global.user.getUserName()));
					params.add(new BasicNameValuePair("tagName", user.getUserName()));
					
					response = HttpUtils.Post(url, params);
					
					if(Global.DEBUG) {
						System.out.println("acceptOrRefuseChat -----------------------------\n" + response);
					}
				} catch(Exception e) {
					Log.e(TAG, "Exception", e);
				}
				if(!StringUtils.isEmpty(response)) {
					JSONManager jManager = new JSONManager();
					boolean isGotJSONObject = jManager.isGotJSONObject(response);
					if(isGotJSONObject) {
						//处理chatID和Time
						for(User member : Global.memberList) {
							if(user.getUserName().equals(member.getUserName())) {
								member.setChatId(user.getChatId());
								member.setTime(user.getTime());
								member.setRealName(user.getRealName());
								member.setImgUrl(user.getImgUrl());
								break;
							}
						}
						
						int count = jManager.getResult();
						String msg = jManager.getMsg();
						System.out.println("------ 得到msg: " + count + ":" + msg);
					}
				}
				TongueTipHealthService.setProcessing(true);
			}
		}.start();
	}
  
  @Override
	public void onBackPressed() {
	  String from = getIntent().getStringExtra("from");
	  if ("TongueTipHealthServiceLiuYan".equals(from)) {
		  startActivity(new Intent(ChatActivity.this, HomeActivity.class));
	  }
		finish();
	}

  @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == 1 && resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
				Log.v("TestFile",
						"SD card is not avaiable/writeable right now.");
				Toast.makeText(this, "请插入SD卡", Toast.LENGTH_LONG).show();
				return;
			}
			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");//
			FileOutputStream b = null;
			File fileDir1 = this.getFilesDir();
			String path = fileDir1.getParent() + File.separator + "tempPic"
					+ File.separator;
			File fileDir2 = new File(path);
			fileDir2.mkdir();
			
			SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss");
			Date  curDate  =  new   Date(System.currentTimeMillis());//获取当前时间     
			String  strName  =  "IMG_" + formatter.format(curDate) + ".jpg";  
			
			fileName = path + strName;
			System.out.println("fileName:" + fileName);
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(mHandler != null) {
            	Message msg = mHandler.obtainMessage(MessageWhat.PICTURE);
            	msg.obj = fileName;
            	msg.sendToTarget();
            }
		} else if (requestCode == 2 && resultCode == Activity.RESULT_OK) {
			Uri uri = data.getData();
			if (uri.toString().contains("file")) {
				//已经是绝对路径，从文件管理器传过来
				fileName = uri.getPath();
			} else {
				//http://www.cnblogs.com/lingyun1120/archive/2012/04/18/2455212.html
				//由从URI获得文件路径
				//从图片库传过来
				String[] proj = { MediaStore.Images.Media.DATA };
				Cursor actualimagecursor = this.managedQuery(uri, proj,
						null, null, null);
				int actual_image_column_index = actualimagecursor
						.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
				actualimagecursor.moveToFirst();
				String img_path = actualimagecursor
						.getString(actual_image_column_index);
				fileName = img_path;
			}
			if(mHandler != null) {
            	Message msg = mHandler.obtainMessage(MessageWhat.PICTURE);
            	msg.obj = fileName;
            	msg.sendToTarget();
            }
		}
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		String from = getIntent().getStringExtra("from");
		System.out.println(from + " ++++++++++++ == onResume ");
	    if(from != null && from.equals("TongueTipHealthService")) {
			getIntent().putExtra("from", "");
	    	user = (User)getIntent().getSerializableExtra("user");
	    	Global.homepageChatWidget2.initCurrentUser(user);
	    	acceptOrRefuseChatDialog();
	    }
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		System.out.println(" ++++++++++++ == onPause ");
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		super.onDestroy();
		
		//homepageChatWidget2.setProcessing(false);
	}
	

}